package com.github.jspxnet.worktask.core.job;

import com.github.jspxnet.utils.BeanUtil;
import com.github.jspxnet.utils.StringUtil;
import com.github.jspxnet.worktask.model.enums.FlowNodeEnumType;
import com.github.jspxnet.worktask.model.enums.WorkTaskEnumType;
import com.github.jspxnet.worktask.table.ConfFlowNode;
import com.github.jspxnet.worktask.table.WorkTask;
import com.github.jspxnet.worktask.util.WorkFlowUtil;
import java.util.Date;
import java.util.List;

public class ScriptJobTask extends BaseTaskAction{
    @Override
    public boolean execute() throws Exception {
        String nodeId = null;
        String script = confFlowJob.getScript();
        if (!StringUtil.isNull(script))
        {
            try {
                nodeId = WorkFlowUtil.runScript(script,variables);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        currentWorkTask.setUsers(workTaskParam.getUsers());
        currentWorkTask.setWorkTaskType(WorkTaskEnumType.SCRIPT.getValue());
        currentWorkTask.setFlowNodeType(FlowNodeEnumType.END.getValue());
        runtimeServiceDAO.update(currentWorkTask,new String[]{"flowNodeType","workTaskType","users"});

        List<ConfFlowNode> nextNodeList = confWorkFlowDAO.getNextList(currentWorkTask.getFlowNo(), currentWorkTask.getNamespace(), currentWorkTask.getNodeId());
        for (ConfFlowNode confFlowNode:nextNodeList)
        {
            if (nodeId!=null&&nodeId.equals(confFlowNode.getNodeId()))
            {
                //不做任何事情,直接到下一节点
                WorkTask workTask = BeanUtil.copy(workTaskParam, WorkTask.class);
                workTask.setNodeId(confFlowNode.getNodeId());
                workTask.setCreateDate(new Date());
                workTask.setUsers(workTaskParam.getUsers());
                runtimeServiceDAO.save(workTask);
            }
        }
        return true;
    }
}
